package com.example.tangyee.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.view.animation.FastOutLinearInInterpolator;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tangyee.R;
import com.example.tangyee.adapter.MyRecyclerViewAdapter;
import com.example.tangyee.bean.Article;
import com.example.tangyee.bean.Exercise;
import com.example.tangyee.utils.ConstantsUtil;
import com.example.tangyee.utils.GetArticlesForType;
import com.example.tangyee.utils.GlideApp;
import com.example.tangyee.utils.SessionidUtils;
import com.lxj.xpopup.XPopup;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class ExerciseActivity extends AppCompatActivity {

    private static final String TAG = "ExerciseActivity";

    private Unbinder mUnbinder;

    @BindView(R.id.back)
    View back;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.fab)
    FloatingActionButton fab;

    @BindView(R.id.loading_view)
    View loadingView;

    private List<Exercise> data = new ArrayList<>();
    private ExerciseAdapter mAdapter;
    private LinearLayoutManager layoutManager;

    private boolean fabIsShow = false;

    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;

    private GetExerciseList mGetExerciseList;

    public static Intent getExerciseActivityIntent(Context context) {
        Intent intent = new Intent(context, ExerciseActivity.class);
        return intent;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exercise);
        mUnbinder = ButterKnife.bind(this);

        /*
         * 下拉刷新
         * */
        refreshLayout.setRefreshHeader(new MaterialHeader(this));
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            if (mGetExerciseList != null) {
                mGetExerciseList.cancel(true);
            }
            ProgressBar progressBar = loadingView.findViewById(R.id.progressBar);
            progressBar.setVisibility(View.GONE);
            TextView textView = loadingView.findViewById(R.id.loading);
            textView.setText("努力加载中···");
            mGetExerciseList = new GetExerciseList();
            mGetExerciseList.execute();
        });

        // 初始化recyclerview
        initRecyclerView();

        mGetExerciseList = new GetExerciseList();
        mGetExerciseList.execute();
    }

    /*初始化RecyclerView*/
    private void initRecyclerView() {
        mAdapter = new ExerciseAdapter(data);
        mRecyclerView.setAdapter(mAdapter);
        layoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    //调用方法
                    if (dy > 0 && fabIsShow) {
                        hide(fab);
                        fabIsShow = false;
                    } else if (dy < 0 && !fabIsShow) {
                        show(fab);
                        fabIsShow = true;
                    }
                }
            });
        }
    }

    private class GetExerciseList extends AsyncTask<Void, Void, List<Exercise>> {

        @Override
        protected List<Exercise> doInBackground(Void... voids) {

            if (isCancelled()) {
                return null;
            }

            List<Exercise> exercises;

            try {
                SessionidUtils.updateSessionId(ExerciseActivity.this);
                Document document = Jsoup.connect(ConstantsUtil.GET_EXERCISES).cookie("ASP.NET_SessionId", SessionidUtils.getSessionId(ExerciseActivity.this)).get();
                Elements lis = document.select("ul.time-axis>li");
                exercises = new ArrayList<>();
                for (Element li : lis) {
                    Exercise exercise = new Exercise();
                    String str = li.select("div.time-axis-date").text();
                    exercise.setDateStr(str);

                    str = li.select("div.time-axis-title").text();
                    exercise.setName(str);

                    str = li.select("p.mui-badge-success").text();
                    exercise.setTime(str);

                    str = li.select("p.mui-badge-danger").text();
                    exercise.setCalorie(str);

                    Log.d(TAG, "doInBackground: " + exercise.toString());

                    exercises.add(exercise);
                }
            } catch (SocketTimeoutException ste) {
                Log.e(TAG, "doInBackground: ", ste);
                return null;
            } catch (IOException e) {
                Log.e(TAG, "doInBackground: ", e);
                return null;
            }
            return exercises;
        }

        @Override
        protected void onPostExecute(List<Exercise> exercises) {
            if (exercises == null) {
                refreshLayout.finishRefresh(false);
                Toast.makeText(ExerciseActivity.this, "请求超时", Toast.LENGTH_SHORT).show();
                return;
            }
            if (exercises.size() == 0) {
                refreshLayout.finishRefresh(true);
                Toast.makeText(ExerciseActivity.this, "暂无数据", Toast.LENGTH_SHORT).show();
            }
            refreshLayout.finishRefresh(true);
            loadingView.setVisibility(View.GONE);
            XPopup.get(ExerciseActivity.this).dismiss("loading");
            show(fab);
            mAdapter.setExercises(exercises);

            ScaleAnimation sa = new ScaleAnimation(1f, 1f, 1.1f, 1f,
                    Animation.RELATIVE_TO_SELF, 0f,
                    Animation.RELATIVE_TO_SELF, 0f);
            sa.setDuration(1000);

            AlphaAnimation aa = new AlphaAnimation(0, 1);
            aa.setDuration(1000);

            AnimationSet as = new AnimationSet(true);
            as.setDuration(1000);
            as.addAnimation(sa);
            as.addAnimation(aa);
            mRecyclerView.startAnimation(as);
        }
    }

    private class ExerciseAdapter extends RecyclerView.Adapter<ExerciseHolder>{

        private List<Exercise> mExercises;

        ExerciseAdapter(List<Exercise> exercises) {
            mExercises = exercises;
        }

        void setExercises(List<Exercise> exercises) {
            mExercises = exercises;
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public ExerciseHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            ExerciseHolder holder = new ExerciseHolder(LayoutInflater.from(ExerciseActivity.this).inflate(R.layout.exercise_item_layout, viewGroup,false));
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull ExerciseHolder exerciseHolder, int i) {
            Exercise exercise = mExercises.get(i);
            exerciseHolder.mTextView1.setText(exercise.getDateStr());
            exerciseHolder.mTextView2.setText(exercise.getName());
            exerciseHolder.mTextView3.setText(exercise.getTime());
            exerciseHolder.mTextView4.setText(exercise.getCalorie());
        }

        @Override
        public int getItemCount() {
            return mExercises.size();
        }
    }

    private class ExerciseHolder extends RecyclerView.ViewHolder{

        TextView mTextView1, mTextView2, mTextView3, mTextView4;

        public ExerciseHolder(@NonNull View itemView) {
            super(itemView);
            mTextView1 = itemView.findViewById(R.id.textView1);
            mTextView2 = itemView.findViewById(R.id.textView2);
            mTextView3 = itemView.findViewById(R.id.textView3);
            mTextView4 = itemView.findViewById(R.id.textView4);
        }
    }

    @OnClick(R.id.back)
    public void back() {
        onBackPressed();
    }

    @OnClick(R.id.fab)
    void addExerciseRecord() {
        Intent intent = new Intent(this, AddExerciseActivity.class);
        /*
        * getX()与getY()方法获取的是View左上角相对于父容器的坐标，当View没有发生平移操作时，getX()==getLeft()、getY==getTop()。
        **/
        intent.putExtra(AddExerciseActivity.EXTRA_CIRCULAR_REVEAL_X, (int) (fab.getX() + fab.getWidth()/2));
        intent.putExtra(AddExerciseActivity.EXTRA_CIRCULAR_REVEAL_Y, (int) (fab.getY() + fab.getHeight()/2));
        startActivityForResult(intent,1);
        // 去除Activity自身动画
        overridePendingTransition(R.anim.no_anim, R.anim.no_anim);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 1) {
            Exercise exercise = data.getParcelableExtra("result");
            if (exercise != null) {
                XPopup.get(ExerciseActivity.this).asLoading().show("loading");
                new GetExerciseList().execute();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mGetExerciseList != null) {
            mGetExerciseList.cancel(true);
        }
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }

    private void show(final View view) {
        view.animate().cancel();
        view.setAlpha(0f);
        view.setScaleY(0f);
        view.setScaleX(0f);
        view.animate()
                .scaleX(1f)
                .scaleY(1f)
                .alpha(1f)
                .setDuration(200)
                .setInterpolator(new LinearOutSlowInInterpolator())
                .setListener(new AnimatorListenerAdapter() {

                    @Override
                    public void onAnimationStart(Animator animation) {
                        view.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {

                    }
                });
    }

    private void hide(final View view) {
        view.animate().cancel();
        view.animate()
                .scaleX(0f)
                .scaleY(0f)
                .alpha(0f)
                .setDuration(200)
                .setInterpolator(new FastOutLinearInInterpolator())
                .setListener(new AnimatorListenerAdapter() {
                    private boolean mCancelled;

                    @Override
                    public void onAnimationStart(Animator animation) {
                        view.setVisibility(View.VISIBLE);
                        mCancelled = false;
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {
                        mCancelled = true;
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                        if (!mCancelled) {
                            view.setVisibility(View.INVISIBLE);
                        }
                    }
                });
    }
}
